<?php

require_once(dirname(dirname(dirname(dirname(__FILE__)))).'/appconf.php');
  
require_once "CMS.class.php";

$local_config = array(
    'this_cgi'       => 'cms/builder/member/imore.php',
    'tmpl'           => array('base_path' => 'cms/builder/member/imore/'), # full path = $this->param('TMPL').$
    'database'       => '',
    'table'          => 'member_imore',
    'cms_auth_group'  => '',
    '#MESSAGE#'      => array(),
);

class cms_builder_member_imore extends CMS{

  function setup(){
    $this->run_modes('list',
                     'edit',
                     
                     'update', 
                     
                     'view', 
                     
                     'add', 
                     'madd', 
                     'showadd', 'edit_after_add',
                     
                     'showdel', 
                     
                     'showsearch','search','clearsearch',
                     
                     'showsetting', 'setting',
                     
                     'showexportdata', 'exportdata',
                     
                     'ajax_update_field',
                     
                     'scan_member_application', 'approve','not_approve',
                     'trap'
                    );
    $this->start_mode('list');
    $this->set_path_info_position(array('id'=>1));
    parent::setup();
  }

  function cgiapp_prerun($rm=''){
    
    parent::cgiapp_prerun($rm); # login, targeted to run CMS_Login.class.php 
    
  }

  function cgiapp_postrun(&$body){
    parent::cgiapp_postrun($body);

    $a_js = array();
    if (method_exists($this, 'inject_js') && count($this->inject_js()) > 0){ // some old CMS.class.php don't support yet
    	$a_js = $this->inject_js();
    }
    
  //	
    
    $login = $this->get_cms_username();
    if (!empty_string($login)){
      array_push($a_js, "\$('#login').html('Hi $login!  <a href=\"/cms/builder/logout.php\" style=\"color:red;\">Logout</a>');");
    }
  
    if ($this->header_type() == 'redirect'){
      return;	
    }
    
    $a_msg = array();
    $a_current_msg = $this->message();
    $a_session_msg = $this->get_message_from_session();
    foreach ($a_session_msg as $msg){
    	array_push($a_msg, $msg);
    }
    foreach ($a_current_msg as $msg){
    	array_push($a_msg, $msg);
    }
    
    $message = '';
    if (count($a_msg)>0){
      $message = implode('<BR>', $a_msg);
      array_push($a_js, "\$(document).ready(function(){ $(\"#dialog-modal\").dialog({height: 140,modal: true});  });");
    }

    if (count($a_js) > 0){
      $temp = "<script>".implode('', $a_js)."</script>";
      if ($message != ''){
        $temp .= html_dialog('Notice', $message);
      }
      $body = preg_replace('/(<!--POSTRUNJS-->)/', $temp, $body, 1);
      
    }
    
  }

#no no login

  // some
  function trap(){
	  $a_msg = $this->message();
	  $message = '';
	  if (count($a_msg)>0){
	    $message = implode('<BR>', $a_msg);
	    $this->tmpl_assign('title', 'Application Error');
	    $this->tmpl_assign('body',  $message);
  	  return $this->load_tmpl($this->param('TMPL'),  'error.html');
    }
    return '';
  }

  function action_list(){
  	if (! $this->user_can('list') ) return $this->trap();
    
    # on_start_list() *removed* - give it a chance to modify FK and TOP

    $dbh_r = $this->db_connect('read');
    $list_control = $this->update_listing_ordering();
    $sqlstr = 'SELECT * FROM '.$this->param('table').
              $this->listing_condition();
    
    $member_type = $this->create_lookup_array($dbh_r, "member_type", 'id', "cname", ' where status=1'); 
    $expert_approval_type = $this->create_lookup_array($dbh_r, "expert_approval_type", 'id', "cname", ' where status=1 '); 
    $salutation_type = $this->create_lookup_array($dbh_r, "salutation_type", 'id', "cname", 'where status=1'); 
    $h_feature = array(
      'member_type'      => array('h:label',         'member_type',     $member_type ,array()),
      'email_status'     => array('ny:label',        'email_status',    ),
      'expert_approval'  => array('h:label',         'expert_approval', $expert_approval_type ,array()),
      'salutation'       => array('h:label',         'salutation',      $salutation_type ,array()),
      '#ROW_FUNCTION#' => 'list_row_function',
      
      '#MULTIPLE#' =>1,
      '#PAGESIZE#' => 20,
      '#PAGELIST#' => '1,2,3',
      '#PAGE#'     => $this->get_param('q', 'page', 1, 'int'),
      '#GET_SELECTED_ID#' => 1,
      
      );
    list($list_data, $a_pagelist, $a_processed_id) = $this->process_select_result($dbh_r, $sqlstr, $h_feature);

	  if (count($list_data) == 0){

      $this->message('No data.');
	  }

    $this->tmpl_assign('user_permission', $this->get_user_permission());
    $this->tmpl_assign('list_control', $list_control);

    $a_search_cond = $this->s_param('cms_builder_member_imore#'.'SEARCH_COND');
    $is_search = empty($a_search_cond)  ? 0: 1;

    $this->tmpl_assign('title_noun', $is_search > 0 ? 'Search Result of' : 'List of');
    $this->tmpl_assign('clear_search_link', $is_search > 0 ? html_link(' [Clear Search Result]', $this->self_url(array('action'=>'clearsearch'))) : '');
    $this->tmpl_assign('list_data', $list_data);
    $this->tmpl_assign('pagelist', $a_pagelist);
    if (method_exists($this, 'get_navigation')){$this->tmpl_assign('navigation', $this->get_navigation(4));}
    
    return $this->load_action_tmpl('list');
  }

  function list_row_function($dbh_r, $h_row){
    $id = $h_row['id'];
    $expert_approval = $h_row['expert_approval'];
    $helper = getModel('CMS_Helper');   
    $member = getModel('CMS_Member');

    $approve_url = '';
    $url = '';
    if($expert_approval == 4){
		$url = $this->param('CGI_URL').'cms/builder/member/imore.php/approve/'.$id;
        //$approve_url = '<span id="approve">'.html_link('通過審批', $url, array('openwin' => 1))."</span>";
//$approve_url = '<span id="approve">'.html_link('通過審批', $url)."</span>";
//$approve_url = '<span class="approve" id="'.$id.'">通過審批</span>';

$approve_url = '<ul class="tableActions"><li><a style="background-color:red;" class="approve" id='.$id.' href="#">通過審批</a></li></ul>';

//$not_approve_url = '<ul class="tableActions"><li><a style="background-color:red;" class="not_approve" id='.$id.' href="#">否決審批</a></li></ul>';
    }

    return array(
      'photo'       => $helper->single_photo($h_row['photo']),
      'info'          => $member->member_type_info($h_row['id'])."<br />$approve_url",
      );
  }

  function update_listing_ordering(){
  	$a_allowed_sorting_field = array();
  	if (count($a_allowed_sorting_field) == 0){
  		return array();
  	}
  	$sortbyfield = $this->s_param('cms_builder_member_imore#'.'sortby');
    #echo $sortbyfield;
    $a_sortbyfield = explode(',', $sortbyfield);
    $h_sortbyfield = array();
    foreach ($a_sortbyfield as $fieldname_order){
    	$a_temp = explode(' ', $fieldname_order);
    	$field = $a_temp[0];
    	$order = isset($a_temp[1])?$a_temp[1]:'';
    	#echo 'F['.$field.'] or['.$fieldname_order.']';
      $h_sortbyfield[$field]= $order;
    }
    
    $list_control = array();
    $a_result = array();
    $count = 0;
  	foreach ($a_allowed_sorting_field as $field){
  	  $sort_order=$this->get_q('sort_'.$field, '');
  	  if ($sort_order == ''){
  	  	if (isset($h_sortbyfield[$field])){
  	    	#echo "{".$h_sortbyfield[$field].'}';
  	  	  $sort_order =  $h_sortbyfield[$field];
     	  } else {
     	  	$sort_order = 'none';
     	  }	
  	  }
  	  
  	  if ($sort_order == 'none' || $sort_order == ''){
        $list_control['sort_'.$field] = html_img('/cms/images/ico/up_down_arrow.gif', '?sort_'.$field.'=desc');
        #array_push ($a_result, $field.' none');
        #echo 'list_control none sort_ '.$field;
  	  } elseif ($sort_order == 'desc'){
  	  	$list_control['sort_'.$field] = html_img('/cms/images/ico/down_arrow.gif', '?sort_'.$field.'=asc');
  	  	array_push ($a_result, $field.' desc');
  	  	#echo 'list_control down sort_ '.$field;
  	  } elseif ($sort_order == 'asc'){
  	  	$list_control['sort_'.$field] = html_img('/cms/images/ico/up_arrow.gif', '?sort_'.$field.'=none');
     	  array_push ($a_result, $field.' asc');
     	  #echo 'list_control up sort_ '.$field;
      }
  	  
  	}
  	
  	$temp = implode(',',$a_result);
  	#echo $temp.']';
  	$this->s_param('cms_builder_member_imore#'.'sortby', $temp);
  	return $list_control;
  }

  function listing_condition(){
    $a_where = array();

    $session_show_all_status = $this->s_param('cms_builder_member_imore#'.'SETTING_SHOWALLSTATUS');
    switch($session_show_all_status){
      case 'status_all':
        break;
      case 'status_0':
        array_push($a_where, "status=0", "and");
        break;
      case 'status_2':
        array_push($a_where, "status=2", "and");
        break;
      case 'status_none': # no status field
        break;
      default:
        array_push($a_where, "status>=1", "and");
        break;
    }	

    $a_search_condition = $this->s_param('cms_builder_member_imore#'.'SEARCH_COND');
    if (is_array($a_search_condition) && !empty($a_search_condition)){
      $a_where = array_merge($a_where, $a_search_condition);
    }

#    #array_push($a_where, "");#
#
#    $a_order = array();
#    $sortbyfield = $this->get_param('s','sortby', 'id');
#    $sortorder   = $this->get_param('s','sortorder', '');#
#
#    $a_sortbyfield = explode(',', $sortbyfield);
#    $a_sortorder   = explode(',', $sortorder);
#
#    foreach ($a_sortbyfield as $sortbyfield){
#      $sortorder = array_shift($a_sortorder);
#
#      array_push($a_order, "$sortbyfield $sortorder");
#   }

    $sortby = $this->s_param('cms_builder_member_imore#'.'sortby');
    if ($sortby == ''){
    	$sortby = ' id desc';
    }

    $final_str = '';
    if (count($a_where) > 0){
      array_pop($a_where);
      $final_str = ' where '.implode(' ', $a_where);
    }
    #if (count($a_order) > 0){
    #  $final_str .= ' order by '.implode(' and ', $a_order);
    #}
    $final_str .= ' order by '.$sortby;
    
    return $final_str;
  }

  function action_edit($id=null){
    if (! $this->user_can('edit') ) return $this->trap();
    if ($id === null){
       $id = $this->get_param('pq','id',  0, 'int');
    }
    
    if ($id == 0
      
      ) throw new CgiappErrorException(100, __METHOD__.' Invalid Parameter!');
    
    $dbh_r = $this->db_connect('read');

    $sqlstr = 'SELECT * FROM '.$this->param('table')." where id=".$id;
    
    $member_type = $this->create_lookup_array($dbh_r, "member_type", 'id', "cname", ' where status=1'); 
    $expert_approval_type = $this->create_lookup_array($dbh_r, "expert_approval_type", 'id', "cname", ' where status=1 '); 
    $salutation_type = $this->create_lookup_array($dbh_r, "salutation_type", 'id', "cname", 'where status=1'); 
    $h_feature = array(
      
      '#ROW_FUNCTION#' => 'edit_row_function',      
      'member_type'      => array('h:list',          'member_type',     $member_type ,array()),
      'email'            => array('f:func',          'email',           'html_fix_edit_text'),
      'phone'            => array('f:func',          'phone',           'html_fix_edit_text'),
      'email_status'     => array('ny:radio',        'email_status',    ),
      'expert_approval'  => array('h:list',          'expert_approval', $expert_approval_type ,array()),
      'expert_reject_reason' => array('f:func',          'expert_reject_reason', 'html_fix_edit_textarea'),
      'acttime'          => array('f:func',          'acttime',         'html_fix_edit_text'),
      'salutation'       => array('h:list',          'salutation',      $salutation_type ,array()),
      'birthday'         => array('f:func',          'birthday',        'html_fix_edit_text'),
      'idcard'           => array('f:func',          'idcard',          'html_fix_edit_text'),
      'email_receive'    => array('f:func',          'email_receive',   'html_fix_edit_text'),
      'expert_application_reject_type' => array('f:func',          'expert_application_reject_type', 'html_fix_edit_text'),
      'status'           => array('status:radio',    'status',          ),
                       );
    
    if ( $this->user_can('approve', 1) ){
    	$h_feature['status'] = array('status:radio',    'status',          );
    } else {
    	$h_feature['status'] = array('status:label',    '',          );
    }	

    list($h_row, $a_pagelist, $a_processed_id) = $this->process_select_result($dbh_r, $sqlstr, $h_feature);
    
    $this->audit_log('edit', $id);
    
    $this->tmpl_assign('edit_data', $h_row[0]);
    
    if (method_exists($this, 'get_navigation')){$this->tmpl_assign('navigation', $this->get_navigation(4));}
    return $this->load_action_tmpl('edit');
  }

  /*edit action row function
   *  this function will run first when processing the row
   */
  function edit_row_function($dbh_r, $h_row){    
    $helper = getModel('CMS_Helper');   
    $member = getModel('CMS_Member');
    return array(
      'photo'        => $helper->single_photo($h_row['photo']),
       'info'          => $member->member_type_info($h_row['id']),
      );
 
  }

  function action_view(){
    if (! $this->user_can('view') ) return $this->trap();
    $id = $this->get_param('pq','id',  0, 'int');
    
    if ($id == 0
      
      ) throw new CgiappErrorException(100, __METHOD__.' Invalid Parameter!');

    $dbh_r = $this->db_connect('read');

    $sqlstr = 'SELECT * FROM '.$this->param('table')." where id=".$id;
    
    $member_type = $this->create_lookup_array($dbh_r, "member_type", 'id', "cname", ' where status=1'); 
    $expert_approval_type = $this->create_lookup_array($dbh_r, "expert_approval_type", 'id', "cname", ' where status=1 '); 
    $h_feature = array(
      
      'member_type'      => array('h:label',         'member_type',     $member_type ,array()),
      'expert_approval'  => array('h:label',         'expert_approval', $expert_approval_type ,array()),
      'status'           => array('status:label',    'status',          ),
                        );

    list($h_row, $a_pagelist, $a_processed_id) = $this->process_select_result($dbh_r, $sqlstr, $h_feature);
    $this->audit_log('view', $id);
    
    $this->tmpl_assign('view_data', $h_row[0]);
    if (method_exists($this, 'get_navigation')){$this->tmpl_assign('navigation', $this->get_navigation(4));}
    return $this->load_action_tmpl('view');
  }

  function action_update(){
    if (! $this->user_can('edit') ) return $this->trap();
    $id = $this->get_param('pq','id',  0, 'int');
    
    if ($id === false
      
      ) throw new CgiappErrorException(100, __METHOD__.' Invalid Parameter!');
    
    $dbh_w    = $this->db_connect('write');
    $original_status = db_select_one($dbh_w, 'select status from '.$this->param('table').' where id=?', $id);

    $h_feature = array(

    );
    $changed = $this->update_table($dbh_w, $this->param('table'), 'HTTP_POST', $h_feature);
    $upload_changed = 0;
    
    if ($changed > 0 || $upload_changed > 0){
      db_do($dbh_w, "update ".$this->param('table')." set lastmodify=NOW() where id=?", array($id)); 
      
      $this->audit_log('update', $id);
    }
    
  if ($changed > 0  || $upload_changed > 0){
    $this->on_after_update(array(), $id);
  }  
  
    if ($this->get_q('subaction') == 'edit_after_update'){
      return $this->action_edit($id);
    }
    return  $this->cms_redirect_default_action( array() );
  }

/*
 * $this->on_after_update(array('oid'=>$oid, 'topid'=>$topid));
 *  oid, topid may be unavailable
 *  $id: id of the record just edited
 */
function on_after_update($h_param, $id){
  // $oid = $param['oid'];

  $dbh_w = $this->db_connect('write');
  list($member_type, $expert_approval) = db_selectrow_array($dbh_w, 'select member_type, expert_approval from '.$this->param('table').' where id=? and status=1', $id);

  if($expert_approval == 5 && $member_type == 1){
     db_do($dbh_w, 'update '.$this->param('table').' set member_type=5 where id=? and status=1', $id);
   }
}

  function action_mupdate(){
    if (! $this->user_can('edit') ) return $this->trap();
    $id = $this->get_param('pq','id',  0, 'int');
    
    $dbh_w  = $this->db_connect('write');
    
    $h_feature = array(
    
    );
    
    //$this->mupdate_modify_feature(\%feature) if ($this->can('mupdate_modify_feature'));

    $a_changed = $this->update_table_multiple_row($dbh_w, $this->param('table'), 'HTTP_POST', $h_feature);

    $a_id = $this->q_param('id');
    foreach ($a_id as $id){
      $upload_changed = 0;
      
      if ($upload_changed > 0 && !in_array($id, $a_changed)){    
         array_push($a_changed, $id);
       } 

    }

    if (count($a_changed)>0){
      $changed = implode(',' , $a_changed);
      db_do($dbh_w, "update ".$this->param('table')." set lastmodify=NOW() where id in ($changed)", array());       
      $this->audit_log('update', $changed);
    }

    return $this->cms_redirect_default_action(array());
  }
    
  function action_showadd(){
    if (! $this->user_can('add') ) return $this->trap();
    
    $dbh_r = $this->db_connect('read');

    $member_type = $this->create_lookup_array($dbh_r, "member_type", 'id', "cname", ' where status=1'); 
    $expert_approval_type = $this->create_lookup_array($dbh_r, "expert_approval_type", 'id', "cname", ' where status=1 '); 
    $h_feature = array(
      
      'member_type'      => array('h:list',          'member_type',     $member_type ,array()),
      'expert_approval'  => array('h:list',          'expert_approval', $expert_approval_type ,array()),
      );
    $h_default_value = array(
      'username' => '',
      'member_type' => '',
      'email' => '',
      'regip' => '',
      'phone' => '',
      'expert_approval' => '',
      'acttime' => '',
      'salutation' => '',
      'birthday' => '',
      'idcard' => '',
      'email_receive' => '',
      'expert_application_reject_type' => '',
      );
                 
    $showadd_data = $this->process_showadd_feature($dbh_r, $h_feature, $h_default_value);

    $this->tmpl_assign('showadd_data', $showadd_data);
    
    if (method_exists($this, 'get_navigation')){$this->tmpl_assign('navigation', $this->get_navigation(4));}
    return $this->load_action_tmpl('showadd');
  }

  function action_add(){
    if (! $this->user_can('add') ) return $this->trap();
    $id = $this->get_param('pq','id',  0, 'int');
    
    $dbh_w    = $this->db_connect('write'); # db_connect default is readonly

    $h_feature = array(
    'addtime'=>'skip','lastmodify'=>'skip', 

    );
    $changed = $this->add_to_table($dbh_w, $this->param('table'), 'HTTP_POST', $h_feature);

    if ($changed > 0 ){
      $id = db_last_insert_id($dbh_w);
      db_do($dbh_w, "update ".$this->param('table')." set addtime=NOW(),lastmodify=NOW() where id=?", array($id)); 
      
    }
    $upload_changed = 0;
     
    $this->audit_log('add', $id);

  if ($this->get_q('subaction') == 'edit_after_add'){
    return $this->action_edit($id);
  }
  
  if ($this->get_q('subaction') == 'showadd_after_add'){
	  return $this->action_showadd();
	}
  
    return $this->cms_redirect_default_action(array());
  }

  function action_madd(){
    if (! $this->user_can('add') ) return $this->trap();
    $id = $this->get_param('pq','id',  0, 'int');
    
    $dbh_w       = $this->db_connect('write');
    $h_feature = array(
    'addtime'=>'skip','lastmodify'=>'skip', 
    #'addtime' => 'addtime', 'lastmodify' => 'lastmodify',
    
    );
    $changed   = $this->add_to_table_multiple_row($dbh_w, $this->param('table'), 'HTTP_POST', $h_feature);

    if (count($a_changed) > 0){
      foreach ($a_changed as $id){
        $row_affected = $dbh_w->exec("update ".$this->param('table')." set lastmodify = NOW() where id = '$id'") ;
      }
    }
    
		if (count($a_changed) > 0){
		  $changed_id = implode(',', $a_changed);
	    $this->audit_log('madd', $changed_id);
	  }
	
    return $this->cms_redirect_default_action(array());
  }

  /*
   *
   */
  function action_del(){
    if (! $this->user_can('del') ) return $this->trap();
    $id = $this->get_param('pq','id',  0, 'int');
    
    $dbh_w  = $this->db_connect('write');
    $h_param = array(

    '#DELETE_MODE#' => 'hidden'
   );
    $this->delete_from_table($dbh_w, $this->param('table'), 'HTTP_POST', $h_param);
    
    db_do($dbh_w, "update ".$this->param('table')." set lastmodify=NOW() where id=?", array($id)); 
    $this->audit_log('del', 'hidden-'.$id);
    
    return $this->cms_redirect_default_action(array());
  }

  function action_mdel(){
    if (! $this->user_can('del') ) return $this->trap();
    $id = $this->get_param('pq','id',  0, 'int');
    
    # input check
    $a_selected   = array();
    $a_keys      = $this->get_q('mselected_id'); // we may support this field as configurable so that not only cms can use
    if (is_array($a_keys) ){
	    foreach ($a_keys as $row_key){    	
	    	if (ctype_digit($row_key)){
	        array_push($a_selected, $row_key);
	      }
	    }
    }
    if (count($a_selected) == 0){
    	$this->message('Please select the ID for records to be deleted!');
      return $this->cms_redirect_default_action(array());    	
    }
    # end input check
    
    $dbh_w  = $this->db_connect('write');
    $h_param = array(
      
      '#DELETE_MODE#' => 'hidden'
      );
    $a_changed = $this->delete_multiple_from_table($dbh_w, $this->param('table'),'HTTP_POST', $h_param);
    
 		if (count($a_changed) > 0){
		  $changed_id = implode(',', $a_changed);
	    db_do($dbh_w, "update ".$this->param('table')." set lastmodify=NOW() where id in ($changed_id)", array()); 
	  }

		if (count($a_changed) > 0){
		  $changed_id = implode(',', $a_changed);
	    $this->audit_log('mdel', 'hidden-'.$changed_id);
	  }
	
    return $this->cms_redirect_default_action(array());
  }

  function action_help(){
  	#if (! $this->user_can('help') ) return $this->trap();
    if (method_exists($this, 'get_navigation')){$this->tmpl_assign('navigation', $this->get_navigation(4));}
  	return $this->load_action_tmpl('help');
  }
/**HELP:__HELP**/

  function action_showsearch(){
    if (! $this->user_can('list') ) return $this->trap();
    $id = $this->get_param('pq','id',  0, 'int');
    
    $dbh_r = $this->db_connect('read');
    $h_default_value = array(
      'username'=>'',# add session support later
      'member_type'=>'',# add session support later
      'email'=>'',# add session support later
      'regip'=>'',# add session support later
      'phone'=>'',# add session support later
      'expert_approval'=>'',# add session support later
      'acttime'=>'',# add session support later
      'salutation'=>'',# add session support later
      'birthday'=>'',# add session support later
      'idcard'=>'',# add session support later
      'email_receive'=>'',# add session support later
      'expert_application_reject_type'=>'',# add session support later
      );

    $member_type = $this->create_lookup_array($dbh_r, "member_type", 'id', "cname", ' where status=1'); 
    $expert_approval_type = $this->create_lookup_array($dbh_r, "expert_approval_type", 'id', "cname", ' where status=1 '); 
    $salutation_type = $this->create_lookup_array($dbh_r, "salutation_type", 'id', "cname", 'where status=1'); 
    $h_feature = array(
      'id' => 'search_int',
      'username' => '',
      'member_type'      => array('h:checkbox',      'member_type',     $member_type ,array()),
      'email' => '',
      'phone' => '',
      'expert_approval'  => array('h:checkbox',      'expert_approval', $expert_approval_type ,array()),
      'salutation'       => array('h:radio',         'salutation',      $salutation_type ,array()),
       'birthday' => 'range',
                 );

    $showsearch_data = $this->process_showsearch_feature($dbh_r, $h_feature, $h_default_value);
    $this->tmpl_assign('showsearch_data', $showsearch_data);

    if (method_exists($this, 'get_navigation')){$this->tmpl_assign('navigation', $this->get_navigation(4));}
    return $this->load_action_tmpl('showsearch');
  }

  function clearsearch(){
  	
    $this->search_clear('cms_builder_member_imore#');
    return $this->cms_redirect_default_action(array());
  }

  function action_search(){
    if (! $this->user_can('list') ) return $this->trap();
    #<!--START:__PSAUTH-->return $this->psauth_no_access() if (not $this->psauth_can_access('search'));<!--END:__PSAUTH-->

    $h_feature = array(
      
      'global_search' => 'username,email',
      );
    list ($flag, $a_condition) = $this->search_build_sql($h_feature);
    if ($flag == 1){
      return $this->errmsg('no_search_input', 2) ;
    }

    if (is_array($a_condition)  && !empty($a_condition)){
      $this->s_param('cms_builder_member_imore#'.'SEARCH_COND', $a_condition);
    }

    return $this->cms_redirect_default_action(array());
  }

  function showexportdata(){
    if (! $this->user_can('export') ) return $this->trap();
    
    if (method_exists($this, 'get_navigation')){$this->tmpl_assign('navigation', $this->get_navigation(4));}
    return $this->load_action_tmpl('showexportdata');
  }

  function action_exportdata(){
    if (! $this->user_can('export') ) return $this->trap();
    $id = $this->get_param('pq','id',  0, 'int');
    
    $dbh_w = $this->db_connect('write');

    $subaction = $this->get_q('subaction');
    if ($subaction != 'csv' && $subaction != 'xml'){
      $this->message('Invalid argument for export.');
      return $this->trap();
    }

    $dbh_r = $this->db_connect('read');

    $h_feature = array(

    ); 
    $sqlstr = 'SELECT * FROM '.$this->param('table').
                $this->listing_condition();

    $this->log_error('cms', 'SQL: '.$sqlstr);

    # to be supported: modify export feature
    #                  fix edit next cms_record_cnt sql
    #                  export for selected id,  : preg_replace('/where/', 'where id in (\'$temp\') and', $sqlstr);
    #                  export for selected field: tagreplace(\$sqlstr, '\*', $setting_export_field);

    $dbh_r = $this->db_connect('read');
    $temp_folder = $this->param('TEMP'); // avoid serve sync overwrite issue

    #$this->header_add(-content_type=>'application/csv-tab-delimited-table', -Content_disposition => "filename=table.csv");
    #"Content-type:application/vnd.ms-excel");
    #"Content-Disposition:filename=abcde.xls");
    switch($subaction){
      case 'csv':
        list($flag, $filename) = $this->export_to_csv($dbh_r, $this->param('table'), $sqlstr, $h_feature, $temp_folder);
        if ($flag == 0){
        	rename($temp_folder.basename($filename), $this->param('WWW').'cms/TEMP/EXPORTDATA/'.basename($filename));
          return $this->redirect($this->param('URL').'cms/TEMP/EXPORTDATA/'.basename($filename));
        }
        break;
      case 'xml':
        #$this->header_props("Content-type: text/xml");
        #header('Content-Type: text/xml');
        #header('Content-Disposition: attachment; filename="example.xml"');
        #header('Content-Transfer-Encoding: binary');

        list($flag, $filename) = $this->export_to_xml($dbh_r, $this->param('table'), $sqlstr, $h_feature, $temp_folder);
        if ($flag == 0){
        	rename($temp_folder.basename($filename), $this->param('WWW').'cms/TEMP/EXPORTDATA/'.basename($filename));
          return $this->redirect($this->param('URL').'cms/TEMP/EXPORTDATA/'.basename($filename));
        }
        break;

    }

    $this->message('Program exception. (export)');
    return $this->trap();
  }

/**START:COPY**/

##COPY_TYPE_FUNC##
  function action_copy(){
    if (! $this->user_can('add') ) return $this->trap();
    $id = $this->get_param('pq','id',  0, 'int');
    
    $dbh_w = $this->db_connect('write');

    $h_param = array(
    
                   );

    list($count, $new_id)=  $this->copy_row_by_key($dbh_w, $this->param('table'), 'id', $id, $h_param);
    #my ($count, $new_id) = $this->copy_row_by_key($dbh, $this->param('table'), 'id', $id, '', %feature);
    /**START:COPY_BY_FK_HAS_CHILD**/
    if ($this->q_param('subaction') == 'with_child'){
      #$this->##PS_SHARE_CHILD_MODULE_PREFIX##copy_by_parent_key($id, $new_id);
    }
    /**END:COPY_BY_FK_HAS_CHILD**/

    return  $this->action_edit($new_id);
  }

/**END:COPY**/

// Supplementary function add here

  // ajas update a field
  function ajax_update_field(){
    $id   = $this->get_q('id', 0, 'int');
    if ($id == 0) return 'invalid ID';

    ################################################
    # General update, common for all
    ################################################

    $dbh_w    = $this->db_connect('write');
    $h_feature = array();
    $changed = $this->update_table($dbh_w, $this->param('table'), 'HTTP_POST', $h_feature);

    if ($changed > 0){
      $row_affected = db_do($dbh_w, "update ".$this->param('table')." set lastmodify = NOW() where id =?", array($id)) ;
    }

    $dbh_r    = $this->db_connect('read');
    $field  = $this->q_param('#FIELD#');
    list ($value) = db_selectrow_array($dbh_r, "select $field from ".$this->param('table')." where id=?", array($id));
//    ### custom, change by type table
//    if ($field == 'aseip'){
//      list ($value) = db_selectrow_array($dbh, "select cname from test.dummy_type where id=?", array($value));
//    return $value;
//    }
//    #####

    return $value;

  }

/* Custom Class Function Implementation start here */

function scan_member_application(){
/*
  $dbh_r = $this->db_connet('read');

  $ids= db_selectcol_array($dbh_r, 'select id from '.$this->param('table').' where status=1 and 
     expert_approval >=1 and expert_approval <=3');

  foreach ($ids as $id){
  }*/
  $search_cond = array('expert_approval=4', 'status=1');
  $this->s_param('cms_builder_member_imore#'.'SEARCH_COND', $search_cond);
  return $this->cms_redirect_default_action();
}

function action_approve(){

  $id = $this->get_param('pq', 'id', '', 's:int');
  $dbh_w = $this->db_connect('write');


  $is_award = db_select_one($dbh_w, 'select points_award from '.$this->param('table').' where id=? and status=1', $id);
  if($is_award == 0){
		$points = getModel('CMS_Points');  
		$points->points_record($id, 'become_expert', '');
		db_do($dbh_w, 'update '.$this->param('table').' set expert_approval=5, member_type=5, points_award=1 where id=? and status=1', $id);
  }else{
		db_do($dbh_w, 'update '.$this->param('table').' set expert_approval=5, member_type=5 where id=? and status=1', $id);
	}
  return 1;

}
function action_cancel_approve(){

  $id = $this->get_param('pq', 'id', '', 's:int');
  $dbh_w = $this->db_connect('write');

  db_do($dbh_w, 'update '.$this->param('table').' set expert_approval=4 where id=? and status=1', $id);
  $this->message('已成功取消審批: '.$id);
//  return $this->cms_redirect_default_action();
  return ;
}
function action_not_approve(){

  $id = $this->get_param('pq', 'id', '', 's:int');
  $dbh_w = $this->db_connect('write');

  db_do($dbh_w, 'update '.$this->param('table').' set expert_approval=6 where id=? and status=1', $id);

  return 1;
}

}//end class

$webapp = new cms_builder_member_imore(
   array('PARAMS' => array_merge($site_global_config, $local_config))
         );
$webapp->run();

/* Custom Helper Function Implementation start here */

?>
